package com.lyl.label.controller;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.NumberChineseFormatter;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.lyl.label.model.entity.Label;
import com.lyl.label.service.LabelService;
import com.lyl.label.utils.ContextHolderUtils;
import com.zyt.zyt_label.excel.LabelExcel;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/label")
@RequiredArgsConstructor
public class LabelController {
    private final LabelService labelService;

    @GetMapping("/tree")
    public List<Label> tree(){
        return labelService.tree();
    }

    @GetMapping("/treeByDesc")
    public List<Label> treeByDesc(){
        return labelService.treeByDesc();
    }

    @GetMapping("/download/{labelGrade:[0123]}")
    public void download(@PathVariable Integer labelGrade) throws IOException {
        HttpServletResponse response = ContextHolderUtils.getResponse();
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(NumberChineseFormatter.format(labelGrade + 1, false, false) + "级标签替换模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcelFactory.write(response.getOutputStream(), LabelExcel.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .head(head(labelGrade))
                .sheet().doWrite(data());
    }

    private List<List<String>> head(Integer labelGrade) {
        List<List<String>> headList = new ArrayList<>();
        headList.add(ListUtil.toList("原标签"));
        headList.add(ListUtil.toList("替换标签" + (labelGrade == 0 ? "" : "(" + NumberChineseFormatter.format(labelGrade + 1, false, false) + "级, 每级使用-分隔)")));
        return headList;
    }

    private List<LabelExcel> data() {
        List<LabelExcel> list = new ArrayList<>();
        list.add(LabelExcel.builder().oldLabel("中介").newLabel("黑中介").build());
        list.add(LabelExcel.builder().oldLabel("车主").newLabel("顺风车主").build());
        list.add(LabelExcel.builder().oldLabel("货主").newLabel("大车主").build());
        return list;
    }
}
